﻿using System;
using System.Text;

namespace Bouyei.GeoCore.Converters
{
    public class JsonExtensions
    {
        //private Encoding encoding = Encoding.UTF8;
        public JsonExtensions(Encoding encoding=null)
        {
            //if(encoding!=null)
            //{
            //    this.encoding = encoding;
            //}
        }

        public string ConvertFrom<T>(T objectValue)
        {
            return Newtonsoft.Json.JsonConvert.SerializeObject(objectValue,new Newtonsoft.Json.JsonSerializerSettings() { 
             Formatting= Newtonsoft.Json.Formatting.Indented,
            });

            //string result = string.Empty;
            //DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
            //using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            //{
            //    serializer.WriteObject(ms, objectValue);
            //    result = encoding.GetString(ms.ToArray());
            //}
            //return result;
        }

        public T ConvertTo<T>(string jsonString)
        {           
            return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(jsonString,new Newtonsoft.Json.JsonSerializerSettings() { 
             FloatParseHandling= Newtonsoft.Json.FloatParseHandling.Double,
             StringEscapeHandling= Newtonsoft.Json.StringEscapeHandling.EscapeNonAscii
            });

            //T result = default(T);// Activator.CreateInstance<T>();
            //DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
            //using (System.IO.MemoryStream ms = new System.IO.MemoryStream(encoding.GetBytes(jsonString)))
            //{
            //    result = (T)serializer.ReadObject(ms);
            //}
            //return result;
        }
    }
}
